﻿<%@ webhandler language="C#" class="file_upload" %>

using System;
using System.Web;

public class file_upload : IHttpHandler, System.Web.SessionState.IRequiresSessionState {
    public void ProcessRequest(HttpContext context) {
		// Authenticate.
		if(authenticateUser(context)) {
			// Process data.
			String output = processData(context);

			// Set document.
			context.Response.ContentType = "text/plain";
			context.Response.ContentEncoding = System.Text.Encoding.UTF8;
			context.Response.Write(output);
		} else {
			// Set document.
			context.Response.ContentType = "text/plain";
			context.Response.ContentEncoding = System.Text.Encoding.UTF8;
			context.Response.Write("{\"strMessage\":\"Authentication failed.\"}");
		}
    }
	public bool authenticateUser(HttpContext context) {
		String qsSessionId = context.Request.QueryString["session_id"];
		int qsUserId = System.Convert.ToInt32(context.Request.QueryString["user_id"]);

		if(qsUserId > 0) {
			// Get upload session id from database user settings.	
			ent.TableUsers t1 = new ent.TableUsers();
			String recordSessionId = String.Empty;
			recordSessionId = (String)t1.getUserSettings(qsUserId)[ent.TableUsers.TBL__user_settings___setting_key_upload_session_id];
			// Match upload session id from request to database.
			if(String.Equals(qsSessionId, recordSessionId)) {
				// Clear upload session id in database.
				//t1.setUserSetting(ent.TableUsers.TBL__user_settings___setting_key_upload_session_id, String.Empty, qsUserId);
				return true;
			}
		}
		return false;
	}
	public String processData(HttpContext context) {
		ent.TableFiles t4 = new ent.TableFiles();
		int qsUserId = System.Convert.ToInt32(context.Request.QueryString["user_id"]);
		String qsMode = context.Request.QueryString["mode"];
		int qsId = System.Convert.ToInt32(context.Request.QueryString["id"]);
		bool hasUploaded = false;
		
		// Get file from HTTP post request and create file object.
		HttpPostedFile filePosted = context.Request.Files[0]; // Filedata

		// Validate file minimum size.
		if(filePosted.ContentLength <= 0) {
			return "{\"strMessage\":\"Error: File empty, zero length file.\"}";
		}
	
		// Get metadata.
		int fileType = 0;
		String fileName = System.IO.Path.GetFileNameWithoutExtension(filePosted.FileName);
		String fileExtension = System.IO.Path.GetExtension(filePosted.FileName).Substring(1).ToLower();

		// Validate file extension.
		System.Data.DataTable dt1 = t4.dynamicSqlSelect(null, ent.TableFiles.TBL__file_filter_extensions, ent.TableFiles.TBL__file_filter_extensions__extension_deleted + " = 0");
		foreach(System.Data.DataRow dr in dt1.Rows) {
			if(String.Equals(fileExtension, dr[ent.TableFiles.TBL__file_filter_extensions__extension_name])) {
				fileType = (int)dr[ent.TableFiles.TBL__file_filter_extensions__extension_file_type];
				break;
			}
		}
		if(fileType <= 0) {
			return "{\"strMessage\":\"Error: Invalid file type.\"}";
		}

		
		// Read file from stream into buffer.
		Byte[] fileBuffer = new Byte[filePosted.ContentLength];
		int fileRead = filePosted.InputStream.Read(fileBuffer, 0, filePosted.ContentLength);
		if(fileRead <= 0) {
			return "{\"strMessage\":\"Error: Cannot read file.\"}";
		}
	
		// Store file to database by mode.
		if(String.Equals(qsMode, "add")) {
			System.Collections.Hashtable p1 = new System.Collections.Hashtable();
			p1.Add(ent.TableFiles.TBL__files__file_type, fileType);
			p1.Add(ent.TableFiles.TBL__files__file_uploader_user_id, qsUserId);
			p1.Add(ent.TableFiles.TBL__files__file_name, fileName);
			p1.Add(ent.TableFiles.TBL__files__file_name_slug, ent.TableFiles.toSlug(fileName));
			p1.Add(ent.TableFiles.TBL__files__file_binary, fileBuffer);
			p1.Add(ent.TableFiles.TBL__files__file_extension, fileExtension);
			p1.Add(ent.TableFiles.TBL__files__file_size_bytes, filePosted.ContentLength);
			p1.Add(ent.TableFiles.TBL__files__file_date_created, DateTime.Now);
			qsId = t4.createFile(p1);
			hasUploaded = true;
		} else if(String.Equals(qsMode, "edit") && qsId > 0) {
			System.Collections.Hashtable p2 = new System.Collections.Hashtable();
			p2.Add(ent.TableFiles.TBL__files__file_id, qsId);
			p2.Add(ent.TableFiles.TBL__files__file_type, fileType);
			p2.Add(ent.TableFiles.TBL__files__file_uploader_user_id, qsUserId);
			p2.Add(ent.TableFiles.TBL__files__file_name, fileName);
			p2.Add(ent.TableFiles.TBL__files__file_name_slug, ent.TableFiles.toSlug(fileName));
			p2.Add(ent.TableFiles.TBL__files__file_binary, fileBuffer);
			p2.Add(ent.TableFiles.TBL__files__file_extension, fileExtension);
			p2.Add(ent.TableFiles.TBL__files__file_size_bytes, filePosted.ContentLength);
			p2.Add(ent.TableFiles.TBL__files__file_date_created, DateTime.Now);
			t4.setFile(p2);
			hasUploaded = true;
		} else {
			return "{\"strMessage\":\"Error: URL's query strings missing.\"}";
		}
		
		// Output data.
		if(hasUploaded && qsId > 0) {
			System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
			sb1.Append("{");
			sb1.AppendFormat("\"{0}\":{1}, ", "intId", qsId);
			sb1.AppendFormat("\"{0}\":{1}, ", "intUserId", qsUserId);
			sb1.AppendFormat("\"{0}\":\"{1}\", ", "strFileName", fileName);
			sb1.AppendFormat("\"{0}\":\"{1}\", ", "strFileExtension", fileExtension);
			sb1.AppendFormat("\"{0}\":\"{1}\", ", "strFileType", fileType);
			sb1.AppendFormat("\"{0}\":{1}, ", "boolHasUploaded", true.ToString().ToLower());
			sb1.AppendFormat("\"{0}\":\"{1}\"", "strMessage", "success");
			sb1.Append("}");
			return sb1.ToString();
		} else {
			return "{\"strMessage\":\"Error: Upload file to database failed.\"}";
		}
	}
	public bool IsReusable {
		get {return false;}
	}
}